package com.lc.zpyh.ui.activity.mine;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.http.request.PublicMsgBean;
import com.lc.zpyh.http.request.QuestionFeedbacktApi;
import com.lc.zpyh.http.request.SelectCanteenBySchoolIdApi;
import com.lc.zpyh.http.request.UpdateImageApi;
import com.lc.zpyh.http.response.SelectCanteenBySchoolBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.ImageSelectActivity;
import com.lc.zpyh.util.SPUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/*
问题反馈
 */
public class FeedbackActivity extends AppActivity {
    @BindView(R.id.tv_choose_school)
    TextView tvChooseSchool;
    @BindView(R.id.tv_choose_food)
    TextView tvChooseFood;
    @BindView(R.id.rl_commect)
    RelativeLayout rlCommect;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    List<String> dataBeanList = new ArrayList<>();
    private String picone="";
    private String pictwo="";
    private String picthree="";
    private BaseQuickAdapter<String, BaseViewHolder> picadater;
    private  String schoolId="";
    private  String foodId="";
    @Override
    protected int getLayoutId() {
        return R.layout.activity_feedback;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        tvChooseSchool.setText(SPUtil.get(this,IntentKey.ADDRESS,""));
        schoolId=SPUtil.get(this,IntentKey.ADDRESSID,"");
        selectCanteenBySchoolId();
        picadatper();

    }
    private void selectCanteenBySchoolId() {
        EasyHttp.post(this)
                .api(new SelectCanteenBySchoolIdApi().setSchoolid(SPUtil.get(this,IntentKey.ADDRESSID,""))).request(new HttpCallback<SelectCanteenBySchoolBean>(this) {

            @Override
            public void onSucceed(SelectCanteenBySchoolBean data) {
                if (data.getCode()==0) {
                    for (int i = 0; i <data.getList().size() ; i++) {
                        if (data.getList().get(i).getName()!=null){
                            tvChooseFood.setText(data.getList().get(i).getName());
                            foodId=data.getList().get(i).getId()+"";
                            return;
                        }
                    }
                }
            }
            @Override
            public void onFail(Exception e) {

            }
        });
    }
    private void picadatper() {
        dataBeanList.add("");
        picadater = new BaseQuickAdapter<String,
                BaseViewHolder>(R.layout.item_comment_select_pic, dataBeanList) {

            @Override
            protected void convert(BaseViewHolder childViewHolder, String bean) {
                    if (bean.isEmpty()){
                        childViewHolder.setVisible(R.id.ll_tips, true);
                    }else {
                        childViewHolder.setVisible(R.id.ll_tips, false);
                    }
//                childViewHolder.setGone(R.id.ll_tips, !bean.isEmpty());
                childViewHolder.setGone(R.id.delete, TextUtils.isEmpty(bean));
                childViewHolder.setGone(R.id.img, TextUtils.isEmpty(bean));
                if (!TextUtils.isEmpty(bean)) {
                    Glide.with(getContext()).load(IntentKey.CAR_IMAGE+bean).into(((ImageView) childViewHolder.getView(R.id.img)));
                }
                childViewHolder.getView(R.id.ll_tips).setOnClickListener(view -> {
                    ImageSelectActivity.start(FeedbackActivity.this, 3, data -> {
                        dataBeanList.clear();
                        for (int i = 0; i <data.size() ; i++) {
                            // 裁剪头像
//                        cropImage(new File(data.get(i)));
                            setLuban(new File(data.get(i)));

                        }



                        Log.e("TAG", "onClick: " + data.size());

                    });
                });
                childViewHolder.getView(R.id.delete).setOnClickListener(view -> {
                    dataBeanList.remove(childViewHolder.getAbsoluteAdapterPosition());
                    if (dataBeanList.size()==0){
                        dataBeanList.add("");
                    }
                    childViewHolder.getBindingAdapter().notifyDataSetChanged();

                });

            }

            @Override
            protected int getDefItemCount() {
                return Math.min(3, dataBeanList.size());

            }
        };
        recyclerView.setAdapter(picadater);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if( resultCode==RESULT_OK&&requestCode==100){
            Bundle bundle = data.getExtras();
            String school =null;
            String food =null;
            if(bundle!=null)
                school=bundle.getString("school");
            food=bundle.getString("food");
            schoolId=bundle.getString("schoolId");
            foodId=bundle.getString("foodId");
            Log.e("text",school);
            tvChooseSchool.setText(school);
            tvChooseFood.setText(food);
        }
    }
    @OnClick({R.id.rl_commect, R.id.btn_keep})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_commect:
                Intent intent = new Intent(this,FeedbackSecondaryActivity.class).putExtra("schoolId",schoolId);

                startActivityForResult(intent,100);
                break;
            case R.id.btn_keep:
                questionFeedback();
                break;
        }
    }

    private void questionFeedback() {
//        if (foodId.isEmpty()||schoolId.isEmpty()){
//            toast("请选择学校食堂");
//            return;
//        }
        if (etContent.getText().toString().trim().isEmpty()){
            toast("请输入反馈意见");
            return;
        }
        Log.e("TAG", "questionFeedback: "+dataBeanList.size());
        if (dataBeanList!=null&&dataBeanList.size()>0){
            if (dataBeanList.size()==1){
                picone=dataBeanList.get(0);
            }
            if (dataBeanList.size()==2){
                picone=dataBeanList.get(0);
                pictwo=dataBeanList.get(1);
            }
            if (dataBeanList.size()==3){
                picone=dataBeanList.get(0);
                pictwo=dataBeanList.get(1);
                picthree=dataBeanList.get(2);
            }
        }
        EasyHttp.post(this)
                .api(new QuestionFeedbacktApi().setToken(SPUtil.get(getContext(), IntentKey.TOKEN, "")).setUserId(SPUtil.get(getContext(), IntentKey.USERID, "")).setMerchantId("").setCanteenId(foodId).setSchoolId(schoolId).setFeedbackContent(etContent.getText().toString().trim()).setImgOne(picone).setImgTwo(pictwo).setImgThree(picthree).setComment_type("1")).request(new HttpCallback<PublicMsgBean>(this) {

            @Override
            public void onSucceed( PublicMsgBean data) {
                if (data.getCode()==0) {
                   toast("反馈已提交");
                   finish();
                }

            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    /**
     * 获取图片文件的格式
     */
    private Bitmap.CompressFormat getImageFormat(File file) {
        String fileName = file.getName().toLowerCase();
        if (fileName.endsWith(".png")) {
            return Bitmap.CompressFormat.PNG;
        } else if (fileName.endsWith(".webp")) {
            return Bitmap.CompressFormat.WEBP;
        }
        return Bitmap.CompressFormat.JPEG;
    }

    private void setLuban(File file) {
        Luban.with(this)
                .load(file)                                   // 传人要压缩的图片列表
                .ignoreBy(100)                                  // 忽略不压缩图片的大小
                // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        updateImage(file, true);
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();    //启动压缩
    }
    /**
     * 上传图片
     */
    private void updateImage(File file, boolean deleteFile) {


        EasyHttp.post(this)
                .api(new UpdateImageApi()
                        .setFile(file))
                .request(new OnHttpListener<PublicMsgBean>() {

                    @Override
                    public void onSucceed(PublicMsgBean data) {
//                        dataBeanList.clear();
                        dataBeanList.add(data.getList());
                        picadater.notifyDataSetChanged();
                    }

                    @Override
                    public void onFail(Exception e) {

                    }
                });
    }
}
